package com.mengtian_tech.tju.dataquery.api.service;

import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.mengtian_tech.tju.dataquery.api.model.tjuOracle.College;


/**
 * 人员进出记录服务类
 * @author wxd56
 */
@Service
public class PersonVisitLogService {
	
	@Autowired
	@Qualifier("jdbcTemplateDataAi")
	JdbcTemplate jdbcTemplateDataAi;
	

	@Autowired
	@Qualifier("jdbcTemplatePersonVisit")
	JdbcTemplate jdbcTemplatePersonVisit;
	
	@Autowired
	EmployeeService employeeService;
	
	@Autowired
	StudentService studentService;
	
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	
	/**
	 * 同步人员入校的数据，每次获取1000条进行同步
	 */
	public synchronized int aysncPersonVisitLog() {
		//查询条件
		String where = "";
		
		//首先获取最近的同步信息
		List<Map<String,Object>> asyncList = this.jdbcTemplateDataAi.queryForList("select * from async_log_person_gate where sync_count > 0 order by id desc limit 0,1");
		if(asyncList.size() > 0) {
			Map<String,Object> map = asyncList.get(0);
			if(map != null && map.get("end_id") != null) {
				where = " where id >  " + map.get("end_id") + " ";
			}
		}
		
		
		Date start = new Date();
		int count = 0;
		BigInteger startId = null;
		BigInteger endId = null;
		Date lastCreateTime = null;
		
		List<Map<String,Object>> list =  this.jdbcTemplatePersonVisit.queryForList("select * from weixin_user.user_gate_log "+ where +" order by id asc LIMIT 0, 1000");
		count = list.size();
		
		try {		
			for(Map<String,Object> item:list) {
				if(startId == null) startId = (BigInteger) item.get("id");
				endId =  (BigInteger) item.get("id");
				lastCreateTime = (Date) item.get("created_at");
								
				insert(item);
			}
			
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			Date end = new Date();
			long seconds = (end.getTime() - start.getTime())/1000;
			
			if(count > 0) {
				//插入数据库记录
				this.jdbcTemplateDataAi.update(
						"insert into async_log_person_gate(task_begin,task_end,sync_count,start_id,end_id,last_create_time,duration) values(?,?,?,?,?,?,?)",
						start,end,count,startId,endId,lastCreateTime,seconds);

			}
						
			
		}
		return count;
		
	}

	private void insert(Map<String, Object> item) {
		try {
			
			
			String srcName = (String) item.get("src_name");
		
			//校区
			int schoolIndex = srcName.indexOf("校区");
			String school = null;
			if(schoolIndex != -1) {
				school = srcName.substring(0,schoolIndex);
			}
			
			//大门
			int gateIndex = srcName.indexOf("门");
			String gate = null;
			if(gateIndex != -1) {
				gate = srcName.substring(schoolIndex+1+1,gateIndex+1);
			}
			
			//方向
			String direction = srcName.indexOf("入口") != -1?"入":"出";
			
			//日期
			Date createTime = (Date) item.get("created_at");
			String dateOn = sdf.format(createTime);

			//小时
			Calendar c = Calendar.getInstance();
			c.setTime(createTime);
			int hourOn = c.get(Calendar.HOUR_OF_DAY);
			
			//获取学院
			String jobNo = (String) item.get("job_no");
			College college = null;
			String collegeId = "-1";
			String collegeName = "";
			
			college = this.studentService.getCollege(jobNo);
			if(college == null) {
				college = this.employeeService.getCollege(jobNo);
			}
			
			if(college != null) {
				collegeId = college.getCollegeId();
				collegeName = college.getCollegeName();
			}
			
			
			this.jdbcTemplateDataAi.update("insert into user_gate_log(name,org_name,card_no,job_no,mobile,send_time,src_name,id_card,event_name,json,created_at,updated_at,log_id,"
					+ "school_area,gate_name,date_on,hour_on,direction,college_id,college_name) "
					+ " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ",
					item.get("name"),item.get("org_name"),item.get("card_no"),item.get("job_no"),item.get("mobile"),item.get("send_time"),item.get("src_name"),
					item.get("id_card"),item.get("event_name"),item.get("json"),item.get("created_at"),item.get("updated_at"),item.get("id"),
					school,gate,dateOn,hourOn,direction,collegeId,collegeName);
			
		}catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	

	//处理学院为空的下一个id
	private Long startIdForHandleCollege = 0l;

	/**
	 * 查找用户身份,可以在定时任务中查找
	 */
	public synchronized  List<Map<String,Object>> getNextHandleCollegeList() {
		 
		 
		List<Map<String,Object>> list =  this.jdbcTemplateDataAi.
				queryForList("SELECT id,job_no from user_gate_log where college_id is null and job_no <> '-'  and   job_no is not null and id > ?   order by id asc  limit 0,2000",startIdForHandleCollege);
		
		if(list.size() > 0) {
			startIdForHandleCollege = new Long( list.get(list.size()-1).get("id").toString());
		}
		
		return list;
		
	}
	
	
	public void updateCollege(String collegeId,String collegeName,Long id) {
		//更新已处理
		this.jdbcTemplateDataAi.update("update  data_ai.user_gate_log set college_id=?,college_name=?  where id = ?",
				collegeId,collegeName,id);
	}
	
}
